﻿/*  March 2011 - Muaz Khan - dtweet
 *   this file handles user home-page
 */

var dtweet_user = {
    childCount: 20, // used in atScrollBottom func
    tweetsTable: $('#tweets'), // caching table element with id 'tweets' (tweets container)
    totalTweets: 0, // total tweets of this user
    tweetCountElement: $('#tweets-count'), // right-top corner of dashboard panel
    alertBy: undefined,            // name of the user who wants to follow a private user
    identity: undefined,           // identity for tracking exact object

    // tweets displayed on the page. if all tweets are displayed on user homepage, it
    // should equal to total-tweets-count
    currentTweetCount: 0,
    processing: false
};

// invoking it after every 5 second
dtweet_user.checkNewTweet = function ()  {
    /*
     According to Nicholas C. Zakas:  http://www.nczonline.net
     'Store out-of-scope (global) variables in local variables'
     http://www.youtube.com/watch?v=mHtdZgou0qU  => his presentation video
     */
    var dUser = dtweet_user;
    var dt = dtweet; // global variable in dtweet.layout.js

    var tweetCount = dUser.totalTweets;

    $.ajax({
        // for domainName global object, open _viewStart.cshtml
        url: domainName + '/Tweet/CheckUserNewTweet',
        type: 'POST',
        data: "tweetCount=" + tweetCount,
        success: function (data) {
            if (data.IsSuccess === true) {
                /*
                 According to Nicholas C. Zakas:  http://www.nczonline.net
                 'Minimise document reflow by only changing the DOM when absolutely necessary'
                 http://www.youtube.com/watch?v=mHtdZgou0qU  => his presentation video
                 */
                var parentOfTable = dUser.tweetsTable.parent();
                dUser.tweetsTable.remove();
                var tweetsData = data.Tweet;

                /*  $.each is not appropriate if performance in mind, but it is easier to use! */
                $.each(tweetsData, function (index, d) {
                    // prepending at top
                    dUser.tweetsTable.prepend('<tr class="tweet"><td class="name-section"><div style="float: left; margin-left: 20px;"><img src="' + domainName + '/Content/images/user.gif" alt="" width="50" class="borders" /></div><strong>'
                            + '<a href="' + domainName + '/user/' + d.UserName + '">'
                            + d.UserName
                            + '</a>'
                            + '</strong><p><abbr class="timeago" title="'
                            + dt.exactDate(d.EventDate) /* dtweet.layout.js */
                            + '">'
                            + dt.exactDate(d.EventDate) /* dtweet.layout.js */
                            + '</abbr></p></td><td class="message-section">'
                            + dt.exactMessage(d.Message) /* dtweet.layout.js */
                            + '</td></tr>');

                    dUser.childCount++;
                });
                var dataCount = data.Count; // caching data.count value
                dUser.totalTweets = dataCount;
                dUser.tweetCountElement.html(dataCount);
                dUser.currentTweetCount = dataCount;
                $('#div-process').hide();
                var trs = dUser.tweetsTable.find('tr');
                if(trs.length > 20)
                {
                     dUser.tweetsTable.find('tr:last-child').remove();
                }
                parentOfTable.append(dUser.tweetsTable); // Nicholas C. Zakas' advise

                dt.setMinHeight();
            }
            else {
                $('#div-process').hide();
            }
            /* according to paul irish, it is better to user setTimeout instead of setInterval for recursive operations */
            setTimeout(dUser.checkNewTweet, 5000);
        },
        error: function () {
            $('#div-process').hide();
            /* according to paul irish, it is better to user setTimeout instead of setInterval for recursive operations */
            setTimeout(dUser.checkNewTweet, 5000);
        }
    });
};

// alert message for current user whose homepage is opened
dtweet_user.getAlert = function () {
    /*
     According to Nicholas C. Zakas:  http://www.nczonline.net
     'Store out-of-scope (global) variables in local variables'
     http://www.youtube.com/watch?v=mHtdZgou0qU  => his presentation video
     */
    var dUser = dtweet_user;

    $.ajax({
        url: domainName + '/Tweet/GetAlert',
        type: 'POST',
        success: function (result) {
            if (result.IsSuccess === false) {
                return; // no alert yet! --- return undefined;
            }
            var divHeader = $('div#header');
            // blocking header section and showing up alert message (jquery.blockUI.js)
            divHeader.block({ message: '<table><tr><td>' + result.Alert.Message + '</td><td style="padding-left:20px;"><button id="accept-button" class="check" title="Ok, let him view my tweets. I approve him."></button> <button id="reject-button" class="uncheck" title="No, don’t let him to view my tweets. I reject him."></button></td></tr></table>',
                css: { 'text-align': 'left', 'cursor': 'auto', width: 'auto', padding: '15px', backgroundColor: 'white', '-webkit-border-radius': '10px', '-moz-border-radius': '10px', opacity: .9 }
            });
            dUser.alertBy = result.Alert.AlertBy;
            dUser.identity = result.Alert.Identity;

            // reject button click event
            $('#reject-button').click(function () {
                dUser.rejectRequest();
                divHeader.unblock(); // jquery.blockUI.js
            });

            // accept button click event
            $('#accept-button').click(function () {
                dUser.allowRequest();
                divHeader.unblock(); // jquery.blockUI.js
            });
        }
    });
    setTimeout(dUser.getAlert, 60000); // every 1 minute
};

dtweet_user.insertTweetsAtPageLoad = function () {
    /*
     According to Nicholas C. Zakas:  http://www.nczonline.net
     'Store out-of-scope (global) variables in local variables'
     http://www.youtube.com/watch?v=mHtdZgou0qU  => his presentation video
     */
    var dUser = dtweet_user;
    var dt = dtweet; // global variable in dtweet.layout.js

    $.ajax(domainName + '/Tweet/InsertUserTweetsAtPageLoad', {
        type: 'POST',
        success: function (data) {
            if (data.IsSuccess === true) // maximum 20 records (list of records)
            {
                /*
                 dtweet.layout.js
                 calling tweetMessage func of dtweet object (Don't repeat yourself rule -DRY)
                 */
                dt.tweetMessage(data, dUser.tweetsTable);
                var dataCount = data.Count; // caching
                dUser.totalTweets = dataCount; // first time initialized
                dUser.currentTweetCount = dataCount;
                $('#div-process').hide();
                dUser.tweetCountElement.html(dataCount); // right-top corner of dashboard element
            }
        }
    }).done(function () {
        /*
         tweets top container 'main-content' is floated left so its height should manually be set.
         dtweet.layout.js
         */
        dt.setMinHeight();

        // after every 5 seconds, check new tweet
        dUser.checkNewTweet();

        // after every 1 minute, check new alert message
        dUser.getAlert();
        $('#div-process').hide();
    });
};

// twitter.com like scroll bottom tweet insertion
dtweet_user.atScrollBottom = function (e) {
    /*
     According to Nicholas C. Zakas:  http://www.nczonline.net
     'Store out-of-scope (global) variables in local variables'
     http://www.youtube.com/watch?v=mHtdZgou0qU  => his presentation video
     */
    var dUser = dtweet_user;
    var dt = dtweet; // global variable in dtweet.layout.js

    $(document).bind('mousemove', function (e) {
        if ($(document).height() < 1200 || dUser.currentTweetCount < dUser.childCount) {
            return; // return undefined;
        }

        if (e.pageY > $(document).height() - 400 && !dUser.processing) {
            dUser.processing = true; // preventing simultaneous ajax requests until one get done

            $.ajax({
                url: domainName + '/Tweet/GetFiveUserTweets',
                type: 'POST',
                data: "tweetCount=" + dUser.childCount,
                success: function (data) {
                    if (data) {
                        dt.tweetMessage(data, dUser.tweetsTable);
                        /* dtweet.layout.js */
                        dUser.childCount = dUser.childCount + 5;
                        dt.setMinHeight();
                        /* dtweet.layout.js */
                    }
                    dUser.processing = false;   // done, next please!
                },
                error: function () {
                    dUser.processing = false;   // error, try again
                }
            });
        }
    });
};

dtweet_user.allowRequest = function () {
    /*
     According to Nicholas C. Zakas:  http://www.nczonline.net
     'Store out-of-scope (global) variables in local variables'
     http://www.youtube.com/watch?v=mHtdZgou0qU  => his presentation video
     */
    var dUser = dtweet_user;

    $.ajax({
        url: domainName + '/Tweet/AllowRequest',
        type: 'POST',
        async: false,   // blocking other asynchronous requests
        data: "alertBy=" + dUser.alertBy + "&identity=" + dUser.identity,
        success: function (result) {
            if (result.IsSuccess === false) {
                alert(result.Message);  // error message
            }
            /*  if ( result.IsSuccess === true ) allowed successfully */
        }
    });
};

dtweet_user.rejectRequest = function () {
    $.ajax({
        url: domainName + '/Tweet/RejectRequest',
        type: 'POST',
        async: false,
        data: "identity=" + dtweet_user.identity,
        success: function (result) {
            if (result.IsSuccess === false) {
                alert(result.Message);
            }
            /* if ( result.IsSuccess === true )rejected successfully */
        }
    });
};

// poshyTip of 'follow private user' button
dtweet_user.poshyTipFollowRequest = function () {
    $('#follow-protected-user').poshytip({
        className: 'tip-twitter',
        alignTo: 'target',
        alignX: 'right',
        alignY: 'center',
        offsetX: 5,
        content: function () {
            return "Make a request to follow this private user";
        }
    });
};

//when user clicks 'follow private user' button
dtweet_user.privateUserFollowRequest = function () {
    $('#follow-protected-user').click(function () {
        var requestFieldset = $('#request-fieldset');

        requestFieldset.block({ message: 'Please wait...', css: { border: 'none', padding: '15px', backgroundColor: '#000', '-webkit-border-radius': '10px', '-moz-border-radius': '10px', opacity: .5, color: '#fff', 'font-size': '20px', width: '47%'} });

        var userName = $(this).attr('class'); // just a trick to access username

        $(this).poshytip('destroy');

        $.ajax({
            url: domainName + '/Tweet/FollowRequest',
            type: 'POST',
            data: "userName=" + userName,
            success: function (result) {
                if (result.IsSuccess === true) // request successfully
                {
                    requestFieldset.html('<p style="margin: 20px;">Your request has sent to ' + userName + '. Now, when he approves, his tweets will visible to you.<br />Best of luck!</p>');
                }
                else // something went wrong
                {
                    requestFieldset.html('<p style="margin: 20px;">' + result.Message + '</p>');
                }

                // not forget to unblock ui (jquery.blockUI.js)
                requestFieldset.unblock();
            }
        });
    });
};

dtweet_user.startupCaller = function () {
    /*
     According to Nicholas C. Zakas:  http://www.nczonline.net
     'Store out-of-scope (global) variables in local variables'
     http://www.youtube.com/watch?v=mHtdZgou0qU  => his presentation video
     */
    var dUser = dtweet_user;
    var dt = dtweet; // global variable in dtweet.layout.js

    var privateUser = $('#isPrivateUser').val(), // private user or public
            userhimself = $('#isCurrentUser').val(), // user himself
            allowedUser = $('#allowed-user').val();
    /*
     if user is a public-user and someone else is viewing his homepage, then
     just show his public tweets to him.
     */
    if (privateUser === 'no') {
        if (userhimself === 'no') {
            // after page load, get 20 latest tweets and append in a table object
            dUser.insertTweetsAtPageLoad();

            // like twitter.com, when user scroll bottom, get 5 additional tweets and display
            // to user
            dUser.atScrollBottom();
        }
        else  /* user is a public user and he himself viewing his homepage  */
        {
            dUser.insertTweetsAtPageLoad();
            dUser.atScrollBottom();
        }

    }
    if (privateUser === 'yes') {
        // someone else wants to view the tweets of a private user
        if (userhimself === 'no' && allowedUser === 'no') {
            $('#main').css('min-height', '350px');
            $('#dashboard').css('min-height', '350px');
            dUser.poshyTipFollowRequest();
            dUser.privateUserFollowRequest();
        }
        if (userhimself === 'no' && allowedUser === 'yes') {
            dUser.insertTweetsAtPageLoad();
        }
        if (userhimself === 'yes') {
            dUser.insertTweetsAtPageLoad();
            dUser.atScrollBottom();
        }
    }
};

$('#new-tweet-button').click(function (e) {
    var message = $('#Message'),
            tTable = $('#tweet-table');
    if (message.val().length < 1) {
        message.focus();
        e.preventDefault();
        return;
    }

    tTable.block({ message: 'tweeting....', css: { 'padding': '20px', 'font-size': '20px',
        'border-bottom-left-radius': '6px 6px',
        'border-bottom-right-radius': '6px 6px',
        'border-top-left-radius': '6px 6px',
        'border-top-right-radius': '6px 6px',
        'box-shadow': '0 0 1px black',
        '-webkit-box-shadow': '0 0 1px black',
        '-moz-box-shadow': '0 0 1px black'
    }
    });

    $.ajax({
        url: domainName + '/tweet/new',
        type: 'POST',
        data: "message=" + message.val(),
        success: function (result) {
            if (result.IsSuccess === false) {
                message.focus();
                alert(result.Message);
                tTable.unblock();
                e.preventDefault();
                $('#div-process').hide();
            }
            else {
                message.val('').focus();
                tTable.unblock();
                $('#div-process').show();
            }
        },
        error: function () {
            message.css('border-color', 'red');
            tTable.unblock();
            $('#div-process').hide();
        }
    });
});